<template>
  <div class="staff-container">
    <h2>员工列表</h2>
    
    <!-- 查询区域 -->
    <div class="search-area">
      <div class="search-item">
        <label>部门：</label>
        <select v-model="searchForm.department">
          <option value="all">全部部门</option>
          <option value="研发">研发</option>
          <option value="行政">行政</option>
          <option value="产品">产品</option>
          <option value="设计">设计</option>
          <option value="测试">测试</option>
          <option value="市场">市场</option>
          <option value="人力资源">人力资源</option>
          <option value="财务">财务</option>
        </select>
      </div>
      <div class="search-item">
        <label>入职时间：</label>
        <select v-model="searchForm.entryYear">
          <option :value="null">请选择年</option>
          <option v-for="year in yearOptions" :key="year" :value="year">{{ year }}</option>
        </select>
        <select v-model="searchForm.entryMonth">
          <option :value="null">请选择月</option>
          <option v-for="month in monthOptions" :key="month" :value="month">{{ month }}</option>
        </select>
      </div>
      <button @click="handleSearch" class="search-btn">查询</button>
    </div>

    <div class="action-buttons">
      <button @click="showAddDialog" class="add-btn">添加员工</button>
    </div>

    <table>
      <thead>
        <tr>
          <!-- <th>员工ID</th> -->
          <th>员工账号</th>
          <th>姓名</th>
          <th>性别</th>
          <th>职位</th>
          <th>入职时间</th>
          <th>工资</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <StaffItem v-for="staff in staffList" :key="staff.user_id" :staff="staff" @edit="editStaff"
          @delete="deleteStaff" @view="viewStaffInfo" />
      </tbody>
    </table>

    <!-- 分页区域 -->
    <div class="pagination-container">
      <div class="total-count">
        共 {{ total }} 条记录，当前第 {{ currentPage }}/{{ totalPages }} 页
      </div>
      <div class="pagination-buttons">
        <button 
          @click="prevPage" 
          :disabled="currentPage === 1"
          class="pagination-btn"
        >
          上一页
        </button>
        <button 
          @click="nextPage" 
          :disabled="currentPage === totalPages"
          class="pagination-btn"
        >
          下一页
        </button>
      </div>
    </div>

    <!-- 添加/编辑员工对话框 -->
    <div v-if="showDialog" class="dialog-overlay">
      <div class="dialog">
        <h3>{{ isEditMode ? '编辑员工' : '添加员工' }}</h3>
        <form @submit.prevent="submitForm">
          <div class="form-group">
            <label>员工账号:</label>
            <input v-model="formData.user_account" required>
          </div>
          <div class="form-group">
            <label>姓名:</label>
            <input v-model="formData.user_name" required>
          </div>
          <div class="form-group">
            <label>性别:</label>
            <select v-model="formData.gender" required>
              <option value="1">男</option>
              <option value="2">女</option>
            </select>
          </div>
          <div class="form-group">
            <label>职位:</label>
            <select v-model="formData.user_position_id" required>
              <option v-for="pos in positions" :key="pos.pos_id" :value="pos.pos_id">
                {{ pos.pos_name }}
              </option>
            </select>
          </div>
          <div class="form-group">
            <label>入职时间:</label>
            <input type="date" v-model="formData.user_entrytime" required>
          </div>
          <div class="dialog-buttons">
            <button type="button" @click="closeDialog">取消</button>
            <button type="submit">保存</button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script>
import StaffItem from '../components/StaffItem.vue';
import axios from '../axios';

export default {
  components: {
    StaffItem
  },
  data() {
    return {
      staffList: [],
      positions: [],
      showDialog: false,
      isEditMode: false,
      formData: {
        user_id: null,
        user_account: '',
        user_name: '',
        gender: '1',
        user_position_id: '',
        user_entrytime: ''
      },
      // 分页相关数据
      currentPage: 1,
      pageSize: 10,
      total: 0,
      totalPages: 1,
      // 查询表单
      searchForm: {
        department: 'all',
        entryYear: null,
        entryMonth: null
      },
      yearOptions: [],
      monthOptions: []
    };
  },
  methods: {
    generateYearOptions() {
      const years = [];
      for (let year = 2000; year <= 2030; year++) {
        years.push(year);
      }
      this.yearOptions = years;
    },
    generateMonthOptions() {
      const months = [];
      for (let month = 1; month <= 12; month++) {
        months.push(month < 10 ? '0' + month : month.toString());
      }
      this.monthOptions = months;
    },
    async fetchStaffList() {
      try {
        let entryTimeParam = null;
        
        if (this.searchForm.entryYear && this.searchForm.entryMonth) {
            entryTimeParam = `${this.searchForm.entryYear}-${this.searchForm.entryMonth}`;
        } else if (this.searchForm.entryYear) {
            entryTimeParam = this.searchForm.entryYear.toString();
        }

        const params = {
          page: this.currentPage,
          pageSize: this.pageSize,
          department: this.searchForm.department,
          entryTime: entryTimeParam 
        };
        
        console.log("Fetching staff list with params:", params);

        const response = await axios.get('/staff/list', { params });
        if (response.data.code === 2000) {
          const { list, total, page, pageSize, totalPages } = response.data.data;
          this.staffList = list;
          this.total = total;
          this.currentPage = page;
          this.pageSize = pageSize;
          this.totalPages = totalPages;
        } else {
            console.error("获取员工列表失败:", response.data.msg);
            this.staffList = [];
            this.total = 0;
            this.currentPage = 1;
            this.totalPages = 1;
        }
      } catch (error) {
        console.error('获取员工列表失败:', error);
        this.staffList = [];
        this.total = 0;
        this.currentPage = 1;
        this.totalPages = 1;
      }
    },
    handleSearch() {
      this.currentPage = 1;
      this.fetchStaffList();
    },
    prevPage() {
      if (this.currentPage > 1) {
        this.currentPage--;
        this.fetchStaffList();
      }
    },
    nextPage() {
      if (this.currentPage < this.totalPages) {
        this.currentPage++;
        this.fetchStaffList();
      }
    },
    viewStaffInfo(staff) {
      this.$router.push({
        name: 'staffInfo',
        params: { id: staff.user_id },
      });
    },
    formatDate(dateString) {
      if (!dateString) return '';
      const date = new Date(dateString);
      if (!isNaN(date.getTime())) {
        // 调整时区，确保日期正确，并加一天
        date.setDate(date.getDate() + 1);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`;
      } else {
        return dateString;
      }
    },
    async fetchPositions() {
      try {
        const response = await axios.get('/staff/positions/list');
        this.positions = response.data.data;
      } catch (error) {
        console.error('获取职位列表失败:', error);
      }
    },
    showAddDialog() {
      this.isEditMode = false;
      this.resetForm();
      this.showDialog = true;
    },
    editStaff(staff) {
      console.log('正在编辑员工:', staff);
      this.isEditMode = true;
      this.formData = {
        user_id: staff.user_id,
        user_account: staff.user_account,
        user_name: staff.user_name,
        gender: staff.user_sex_id.toString(),
        user_position_id: staff.user_position_id,
        user_entrytime: this.formatDate(staff.user_entrytime)
      };
      this.showDialog = true;
    },
    getPositionId(posName) {
      const pos = this.positions.find(p => p.pos_name === posName);
      return pos ? pos.pos_id : '';
    },
    resetForm() {
      this.formData = {
        user_id: null,
        user_account: '',
        user_name: '',
        gender: '1',
        user_position_id: '',
        user_entrytime: ''
      };
    },
    closeDialog() {
      this.showDialog = false;
    },
    async submitForm() {
      try {
        const payload = {
          user_id: this.formData.user_id,
          user_account: this.formData.user_account,
          user_name: this.formData.user_name,
          user_sex_id: parseInt(this.formData.gender),
          user_position_id: parseInt(this.formData.user_position_id),
          user_entrytime: this.formData.user_entrytime
        };

        console.log('Submitting form with payload:', payload);

        if (this.isEditMode) {
          await axios.put(`/staff/${this.formData.user_id}`, payload);
        } else {
          await axios.post('/staff', payload);
        }

        this.fetchStaffList();
        this.closeDialog();
      } catch (error) {
        console.error('保存员工信息失败:', error);
      }
    },
    async deleteStaff(userId) {
      try {
        await axios.delete(`/staff/${userId}`);
        this.fetchStaffList();
      } catch (error) {
        console.error('删除员工失败:', error);
      }
    },
    // 添加一个用于显示性别的计算属性
    getGenderText(genderId) {
      return genderId === 1 ? '男' : '女';
    }
  },
  created() {
    this.generateYearOptions();
    this.generateMonthOptions();
    this.fetchStaffList();
    this.fetchPositions();
  }
};
</script>

<style scoped>
.staff-container {
  margin-top: 80px;
  padding: 20px;
  background-color: #f8f9fa;
}

h2 {
  color: #007bff;
  margin-bottom: 20px;
}

.search-area {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
  padding: 15px;
  background-color: white;
  border-radius: 5px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  align-items: center;
}

.search-item {
  display: flex;
  align-items: center;
  gap: 10px;
}

.search-item label {
    font-weight: bold;
    color: #555;
}

.search-item select {
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  min-width: 80px;
}

.search-item input[type="month"],
.search-item input[type="number"] {
  display: none;
}

.search-btn {
  padding: 8px 16px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.search-btn:hover {
  background-color: #0056b3;
}

.action-buttons {
  margin-bottom: 20px;
}

.add-btn {
  background-color: #28a745;
  color: white;
  padding: 10px 15px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  font-size: 16px;
  transition: background-color 0.3s ease;
}

.add-btn:hover {
  background-color: #218838;
}

table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 20px;
}

th,
td {
  padding: 12px 15px;
  text-align: center;
  border-bottom: 1px solid #ddd;
}

th {
  background-color: #007bff;
  color: white;
  font-weight: 500;
}

tr:nth-child(even) {
  background-color: #f2f2f2;
}

tr:hover {
  background-color: #e9ecef;
}

.pagination-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  padding: 15px;
  background-color: white;
  border-radius: 5px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.pagination-buttons {
  display: flex;
  gap: 10px;
}

.pagination-btn {
  padding: 8px 16px;
  border: 1px solid #007bff;
  background-color: white;
  color: #007bff;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.pagination-btn:hover:not(:disabled) {
  background-color: #007bff;
  color: white;
}

.pagination-btn:disabled {
  border-color: #ccc;
  color: #ccc;
  cursor: not-allowed;
}

.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.dialog {
  background-color: white;
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  width: 400px;
  max-width: 90%;
}

.dialog h3 {
  margin-top: 0;
  color: #007bff;
  border-bottom: 1px solid #eee;
  padding-bottom: 10px;
  margin-bottom: 20px;
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  font-weight: bold;
  color: #555;
}

.form-group input,
.form-group select {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  box-sizing: border-box;
}

.search-item select {
    width: auto; 
    min-width: 80px;
}

.dialog-buttons {
  margin-top: 20px;
  text-align: right;
}

.dialog-buttons button {
  padding: 10px 15px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  font-size: 14px;
  margin-left: 10px;
}

.dialog-buttons button[type="button"] {
  background-color: #6c757d;
  color: white;
}

.dialog-buttons button[type="button"]:hover {
  background-color: #5a6268;
}

.dialog-buttons button[type="submit"] {
  background-color: #007bff;
  color: white;
}

.dialog-buttons button[type="submit"]:hover {
  background-color: #0056b3;
}
</style>